package wci.frontend.c;

import wci.frontend.Token;
import wci.frontend.Parser;
import wci.message.Message;

import static wci.frontend.c.CErrorCode.TOO_MANY_ERRORS;
import static wci.message.MessageType.SYNTAX_ERROR;


/**
 * CErrorHandler
 * 
 *	Used for Syntax errors
 *
 *	-- based on PascalErrorHandler --
 */

public class CErrorHandler
{
	private static final int MAX_ERRORS = 25;
	
	private static int errorCount = 0;

	
	/**
	 * Flags an error within the source
	 * @param token the bad token
	 * @param errorCode error code
	 * @param parser parser
	 */
	public void flag(Token token, CErrorCode errorCode, Parser parser)
	{
		parser.sendMessage(new Message(SYNTAX_ERROR,
										new Object[] {token.getLineNumber(),
													  token.getPosition(),
													  token.getText(),
													  errorCode.toString()}));
		if (++errorCount > MAX_ERRORS) {
            abortTranslation(TOO_MANY_ERRORS, parser);
        }
	}
	
	/**
     * Abort the translation.
     * @param errorCode the error code.
     * @param parser the parser.
     */
	public void abortTranslation(CErrorCode errorCode, Parser parser)
	{
		// Notify the parser's listeners and then abort.
        String fatalText = "FATAL ERROR: " + errorCode.toString();
        parser.sendMessage(new Message(SYNTAX_ERROR,
                                       new Object[] {0,
                                                     0,
                                                     "",
                                                     fatalText}));
        System.exit(errorCode.getStatus());
	}

	/**
	 * getter
	 * @return error count
	 */
	public int getErrorCount() {
		return errorCount;
	}	
}